import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getShopCartListAsync, changeShopCartNumAsync } from '@/store/modules/shopcart'

export default function ShopCart() {
    const list = useSelector((state) => {
        console.log('state', state);
        return state.shopcart.shopcartList
    })
    const dispatch = useDispatch()
    useEffect(() => {
        dispatch(getShopCartListAsync)
    }, [])

    const changeShopCartNum = (_id, op) => {
        switch (op) {
            case '+':
                dispatch(changeShopCartNumAsync({ _id, n: 1 }))
                break
            case '-':
                dispatch(changeShopCartNumAsync({ _id, n: -1 }))
                break
        }

    }
    return (
        <div>
            <h1>购物车</h1>
            <table>
                <thead>
                    <tr>
                        <td>编号</td>
                        <td>名称</td>
                        <td>价格</td>
                        <td>数量</td>
                        <td>小计</td>
                    </tr>
                </thead>
                <tbody>
                    {
                        list.map((item, index) => <tr key={item._id}>
                            <td>{item._id}</td>
                            <td>{item.name}</td>
                            <td>{item.price}</td>
                            <td>
                            <button onClick={() => {
                                    changeShopCartNum(item._id, '-')
                                }}>-</button>
                                {item.num}
                                <button onClick={() => {
                                    changeShopCartNum(item._id, '+')
                                }}>+</button>
                            </td>
                            <td>{item.num * item.price}</td>
                        </tr>)
                    }
                </tbody>
            </table>
        </div>
    )
}
